package compare;


import org.springframework.util.CollectionUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * 对比两个对象的差值
 */
public abstract class CompareObejct<T> {

    private T original;

    private T current;


    public abstract Set getFieldSet();

    public abstract void setFieldSet(Set fieldSet);

    private Set fieldSet;
    /**
     *
     * @param cls
     * @return
     */
    public String contrastObj(Class<T> cls){
        StringBuilder sb = new StringBuilder();
        try{
            Field[] fields = cls.getDeclaredFields();
            for(Field field: fields){
                if(!CollectionUtils.isEmpty(fieldSet)&&!fieldSet.contains(field.getName())){
                    continue;
                }
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(),cls);
                Method getMethod = pd.getReadMethod();
                String type = field.getType().getName();
                if(!"java.util.Set".equals(type)){
                    Object o1 = getMethod.invoke(this.original);
                    Object o2 = getMethod.invoke(this.current);
                    if(null != o2){
                        String s1 = o1 == null ? "" :o1.toString();
                        String s2 = o2 == null ? "" :o2.toString();
                        if(!s1.equals(s2)){
                            //System.out.println("不一样的属性：" + field.getName() + " 属性值：[" + s1 + "," + s2 + "]");
                            sb.append(field.getName() + ":" + "[" + s1 + "," + s2 + "];");
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }


    public T getOriginal() {
        return original;
    }

    public void setOriginal(T original) {
        this.original = original;
    }

    public T getCurrent() {
        return current;
    }

    public void setCurrent(T current) {
        this.current = current;
    }

    /*public static void main(String[] args) {
        User oldUser = new User();
        oldUser.setLenovoId("123");
        oldUser.setMemberCode("555");
        User newUser = new User();
        newUser.setLenovoId("456");
        newUser.setMemberCode("777");
        CompareObejct<User> compareObejct = new CompareObejct();
        compareObejct.setOriginal(oldUser);
        compareObejct.setCurrent(newUser);
        String updateContrast = compareObejct.contrastObj(User.class);
        System.out.println(updateContrast);
    }*/
}